package com.wwwarehouse.usercenter.fragment.register;

import android.Manifest;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.wwwarehouse.common.BuildConfig;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.activity.media.ClipImageActivity;
import com.wwwarehouse.common.bean.upload.FileUploadBean;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.FileUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PermissionUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.common.UserCenterCommon;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

import static android.app.Activity.RESULT_OK;

/**
 * @创建者 chenchao.
 * @创建时间 2017/9/11 13:30
 * @描述 ${TODO}
 */

public class RCShootingHeadFragment extends RegisterCardBaseFragment implements View.OnClickListener, PermissionUtils.PermissionCallbacks {

    private View mView;
    private String mHeadPhoto = "headphoto.jpg";
    private FileUtils    mFileUtils;
    private List<String> mHeadList;
    private String       mImagePath;
    private LinearLayout mLlHeadPhotoFirst;
    private ImageView    mIvHead;
    private TextView     mTvReShoot;
    private Button       mBtSure;
    private ProgressBar  mProgressBar;
    private File         mHeadPhotoFile;
    Uri uri;
    private ValueAnimator       mProAnimator;
    private DisplayImageOptions mDisplayImageOptions;

    @Override
    public void setTitle() {
        if (peekFragment() instanceof RCShootingHeadFragment) {
            mActivity.setTitle(R.string.shooting_head);
        }
    }

    @Override
    public void requestDatas() {
        if (UserCenterCommon.getInstance().getAbsolutePath() != null) {
            mLlHeadPhotoFirst.setVisibility(View.INVISIBLE);
            mIvHead.setVisibility(View.VISIBLE);
            mTvReShoot.setVisibility(View.VISIBLE);
            mBtSure.setEnabled(true);
            BaseApplication.getApplicationInstance().displayRoundImgPixel("file://"+ UserCenterCommon.getInstance().getAbsolutePath(),mIvHead, ConvertUtils.dip2px(mActivity,3));
            BaseApplication.getApplicationInstance().clearMomeryCache("file://" + mImagePath);
//            ImageLoader.getInstance().displayImage("file://"+UserCenterCommon.getInstance().getAbsolutePath(),mIvHead, mDisplayImageOptions);
//            ImageLoader.getInstance().getMemoryCache().remove("file://"+UserCenterCommon.getInstance().getAbsolutePath());
//            ImageLoader.getInstance().getDiskCache().remove("file://"+UserCenterCommon.getInstance().getAbsolutePath());
        }

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_shooting_head, container, false);
        initView();
        return mView;
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.ll_head_photo_first || i == R.id.iv_head) {
            PermissionUtils.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        } else {
            if (i == R.id.bt_sure) {
                EventBus.getDefault().post("RCShootingHeadFragment");
                popFragment();
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == 0) {
            PermissionUtils.permissionDialog(mActivity, perms, null);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (perms.size() == 3) {
            switch (requestCode) {
                case 0:
                    takePhoto(mHeadPhoto);
                    Constant.isTakePhotoFinished = false;
                    break;
            }
        }
    }

    private void takePhoto(String photoName) {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

        if (mHeadPhotoFile == null) {
            mHeadPhotoFile = mFileUtils.getImagesFile(photoName);
        }
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileProvider", mHeadPhotoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, 0);
        } else {
            uri = Uri.fromFile(mHeadPhotoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);  //存储拍照的位置
            startActivityForResult(intent, 0); //开启照相机界面
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0://拍完回来就上传照片
                    if (mHeadPhotoFile != null) {
                        Intent intent = new Intent(getActivity(), ClipImageActivity.class);
                        intent.putExtra("key_select_image_path", mHeadPhotoFile.getAbsolutePath());
                        startActivityForResult(intent, 1);
                    }
                    break;
                case 1:
                    if (data != null) {
                        mLlHeadPhotoFirst.setVisibility(View.INVISIBLE);
                        //上传图片
                        mImagePath = data.getStringExtra("key_select_image_path");
                        List<String> list = new ArrayList<>();
                        list.add(mImagePath);
                        uploadPhoto(list);
                        mIvHead.setVisibility(View.VISIBLE);
                        mTvReShoot.setVisibility(View.VISIBLE);
                        mBtSure.setEnabled(true);
                        UserCenterCommon.getInstance().setAbsolutePath(mImagePath);
                        BaseApplication.getApplicationInstance().displayRoundImgPixel("file://" + mImagePath, mIvHead, ConvertUtils.dip2px(mActivity, 3));
                        BaseApplication.getApplicationInstance().clearMomeryCache("file://" + mImagePath);
//                        BaseApplication.getApplicationInstance().clearSingleImageCache("file://" + mImagePath);

//                        ImageLoader.getInstance().displayImage("file://"+mImagePath,mIvHead, mDisplayImageOptions);
//                        ImageLoader.getInstance().getMemoryCache().remove("file://"+mImagePath);
//                        ImageLoader.getInstance().getDiskCache().remove("file://"+mImagePath);
                    }
                    break;
                default:
                    break;
            }
        }

    }

    private void uploadPhoto(List<String> list) {
        try {
            NoHttpUtils.httpUploadFileRequest(Constant.URL_UPLOADS_AVATAR, list, new NoHttpUtils.OnFileUploadListener() {
                @Override
                public void onStart(int position) {

                }

                @Override
                public void onCancel(int position) {

                }

                @Override
                public void onProgress(int position, int progress) {
                    LogUtils.showLog(progress+"++++++++++++++++++");
                    if (progress < 100) {
                        mProgressBar.setVisibility(View.VISIBLE);
                        mProgressBar.setProgress(progress);
                        startAnimation();
                    }
                    if (progress == 100) {
                        mProgressBar.setVisibility(View.INVISIBLE);
                    }
                }

                @Override
                public void onFinish(int position) {

                }

                @Override
                public void onError(int position, Exception exception) {

                }
            }, new NoHttpUtils.OnFileUploadResultListener() {
                @Override
                public void onSucceed(int what, FileUploadBean fileUploadBean) {
                    //                    dismissProgressDialog();
                    if ("0".equals(fileUploadBean.getCode())) {
                        if (fileUploadBean.getData() != null && fileUploadBean.getData().size() > 0) {
                            List<FileUploadBean.DataBean> data = fileUploadBean.getData();
                            UserCenterCommon.getInstance().setFace(data.get(0).getPath());
                        }
                        LogUtils.showInfoLog(uri.toString());
                    } else {
                    }


                }

                @Override
                public void onFailed(int what, FileUploadBean fileUploadBean) {
                }
            });
        } catch (Exception e) {
            LogUtils.showLog(e.toString());
        }

    }

    private void initView() {
        mFileUtils = new FileUtils();
        mLlHeadPhotoFirst = findView(mView, R.id.ll_head_photo_first);
        mLlHeadPhotoFirst.setOnClickListener(this);
        mIvHead = findView(mView, R.id.iv_head);
        mIvHead.setOnClickListener(this);
        mTvReShoot = findView(mView, R.id.tv_re_shoot);
        mBtSure = findView(mView, R.id.bt_sure);
        mBtSure.setOnClickListener(this);
        mProgressBar = findView(mView, R.id.pb);


//        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mActivity).build();
//        ImageLoader.getInstance().init(config);
//        mDisplayImageOptions = new DisplayImageOptions.Builder()
//                .displayer(new RoundedBitmapDisplayer(ConvertUtils.dip2px(mActivity,3)))
//                .build();


    }

    private int start = 0;
    private void startAnimation() {
        mProAnimator = ValueAnimator.ofInt(start, mProgressBar.getProgress());
        start = mProgressBar.getProgress();
        mProAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animator) {
                //获得当前动画的进度值，整型，1-100之间
                int currentValue = (Integer) animator.getAnimatedValue();
                mProgressBar.setProgress(currentValue);
            }
        });
        mProAnimator.setDuration(1000);
        mProAnimator.start();
        LogUtils.showLog(mProgressBar.getProgress()+"============");

    }

    @Override
    public void onResume() {
        super.onResume();
        Constant.isTakePhotoFinished = true;
    }


    //        private String getImageIdFromPath(String fileName) {
    //
    //            //select condition.
    //            String whereClause = MediaStore.Images.Media.DATA + " = '" + fileName + "'";
    //
    //            //colection of results.
    //            Cursor cursor = mActivity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, whereClause, null, null);
    //            if (cursor == null || cursor.getCount() == 0) {
    //                if (cursor != null)
    //                    cursor.close();
    //                return null;
    //            }
    //            cursor.moveToFirst();
    //            //image id in image table.
    //            String imageId = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID));
    //            cursor.close();
    //            if (imageId == null) {
    //                return null;
    //            }
    //
    //            return imageId;
    //        }
    //
    //        private Bitmap getThumbnailsFromImageId(String imagePath) {
    //            String imageId = getImageIdFromPath(imagePath);
    //            if (imageId == null || imageId.equals("")) {
    //                return BitmapFactory.decodeFile(UserCenterCommon.getInstance().getAbsolutePath());
    //            }
    //
    //            Bitmap bitmap = null;
    //            BitmapFactory.Options options = new BitmapFactory.Options();
    //            options.inDither = false;
    //            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    //
    //            long imageIdLong = Long.parseLong(imageId);
    //            //via imageid get the bimap type thumbnail in thumbnail table.
    //            bitmap = MediaStore.Images.Thumbnails.getThumbnail(mActivity.getContentResolver(), imageIdLong, MediaStore.Images.Thumbnails.MINI_KIND, options);
    //
    //            if (bitmap == null) {
    //                Bitmap b = BitmapFactory.decodeFile(UserCenterCommon.getInstance().getAbsolutePath());
    //                bitmap = b;
    //            }
    //
    //            return bitmap;
    //        }
}
